package com.personal.system.service.impl.content.web;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.personal.common.result.Result;
import com.personal.system.entity.content.Category;
import com.personal.system.entity.content.Tags;
import com.personal.system.entity.content.WebConfig;
import com.personal.system.entity.vo.ApiArticleListVO;
import com.personal.system.entity.vo.SystemArticleListVO;
import com.personal.system.mapper.content.ArticleMapper;
import com.personal.system.mapper.content.CategoryMapper;
import com.personal.system.mapper.content.TagsMapper;
import com.personal.system.mapper.content.WebConfigMapper;
import com.personal.system.service.content.web.ApiHomeService;
import com.personal.system.constant.redis.RedisService;
import com.xxl.job.core.util.IpUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Service
@RequiredArgsConstructor
public class ApiHomeServiceImpl implements ApiHomeService {

    private final RedisService redisService;

    private final WebConfigMapper webConfigMapper;

    private final ArticleMapper articleMapper;

    private final TagsMapper tagsMapper;

    private final CategoryMapper categoryMapper;


    /**
     * 添加访问量
     * @return
     */
    public Result report() {
        // 获取ip
        String ipAddress = IpUtil.getIp();
        // 通过浏览器解析工具类UserAgent获取访问设备信息
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 通过浏览器解析工具类UserAgent获取访问设备信息
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        // 生成唯一用户标识
        String uuid = ipAddress + browser.getName() + operatingSystem.getName();
        String md5 = DigestUtils.md5DigestAsHex(uuid.getBytes());
        // 判断是否访问
        if (!redisService.sIsMember("unique_visitor", md5)) {
            // 访客量+1
            redisService.incr("unique_visitor_count", 1);
            // 保存唯一标识
            redisService.sAdd("unique_visitor", md5);
        }
        // 访问量+1
        redisService.incr("blog_views_count", 1);

        return Result.ok();
    }

    /**
     * 获取首页数据
     * @return
     */
    public Result getHomeData() {
        //获取首页轮播
        List<SystemArticleListVO> articles = articleMapper.selectListByBanner();
        //获取标签云
        List<Tags> tags = tagsMapper.selectList(null);
        //推荐文章
        List<ApiArticleListVO> apiArticleListVOS = articleMapper.selectRecommendArticle();

        return Result.ok().putExtra("articles",articles).putExtra("newArticleList",apiArticleListVOS).putExtra("tagCloud",tags);

    }

    /**
     * 获取网站相关信息
     * @return
     */
    public Result getWebSiteInfo() {
        //网站信息
        WebConfig webConfig = webConfigMapper.selectOne(new LambdaQueryWrapper<WebConfig>()
                .select(WebConfig::getAuthorAvatar,WebConfig::getIsMusicPlayer,WebConfig::getAuthorInfo,WebConfig::getTouristAvatar,WebConfig::getBulletin,
                        WebConfig::getQqNumber,WebConfig::getGitee,WebConfig::getGithub,WebConfig::getLogo,WebConfig::getWechat,
                        WebConfig::getAboutMe,WebConfig::getEmail,WebConfig::getShowList,WebConfig::getLoginTypeList,
                        WebConfig::getRecordNum,WebConfig::getAuthor,WebConfig::getAliPay,WebConfig::getWeixinPay,
                        WebConfig::getQqGroup,WebConfig::getWebUrl, WebConfig::getSummary,WebConfig::getName,WebConfig::getKeyword));

        //获取访问量
        Object count = redisService.get("blog_views_count");
        //获取访客量
        Long visitorAccess = redisService.getCacheSetKeyNumber("unique_visitor");
        //热门文章
        List<ApiArticleListVO> hotArticles = articleMapper.selectHotArticleList();

        return Result.ok(webConfig).putExtra("siteAccess", Optional.ofNullable(count).orElse(0))
                .putExtra("visitorAccess",visitorAccess).putExtra("hotArticles",hotArticles);
    }

    /**
     * 获取各大平台的热搜
     * @param type 平台
     * @return
     */
    @Override
    public Result hot(String type) {
        String url = "https://www.coderutil.com/api/resou/v1/" + type;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access-key", "f94be500c45148bc185be24a38c04ad3");
        paramMap.put("secret-key", "27563ca627d5db0d57e831ca4de0f75f");
        String result= HttpUtil.get(url, paramMap);
        return Result.ok(JSONObject.parseObject(result));
    }

    @Override
    public Result selectCategoryList() {
        List<Category> list = categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByDesc(Category::getSort));
        return Result.ok(list);
    }
}
